package com.yourenbang.lingyun.transaction.web.service.impl.migrate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import com.yourenbang.lingyun.constants.Constant;
import com.yourenbang.lingyun.constants.enums.ChannelIdEnums;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.core.util.BizAssertUtils;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.redis.RedisUtils;
import com.yourenbang.lingyun.domain.MerchantReach20;
import com.yourenbang.lingyun.domain.MerchantReach20Example;
import com.yourenbang.lingyun.mapper.MerchantReach20Mapper;
import com.yourenbang.lingyun.mapper.UserBaseExtMapper;
import com.yourenbang.lingyun.transaction.config.AcmTransactionParams;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.QueryTableDateDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.QueryTablePageDTO;
import com.yourenbang.lingyun.transaction.web.domain.po.klks.UserReach;
import com.yourenbang.lingyun.transaction.web.service.migrate.MerchantReachBatchMigrateService;
import com.yourenbang.lingyun.transaction.web.service.migrate.MerchantReachMigrateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class MerchantReachBatchMigrateServiceImpl extends AbstractMigrateService implements MerchantReachBatchMigrateService {

    @Autowired
    private RedisUtils redis;
    @Autowired
    private AcmTransactionParams acmTransactionParams;
    @Autowired
    private UserBaseExtMapper userBaseExtMapper;
    @Autowired
    private CommonMigrateServiceImpl commonMigrateService;
    @Autowired
    private MerchantReachMigrateService merchantReachMigrateService;
    @Autowired
    private MerchantReach20Mapper merchantReach20Mapper;


    @Override
    public boolean migrateMerchantReachPage(QueryTablePageDTO dto) {

        String uri = "/query/pay/base/query/limit";
        String url = acmTransactionParams.getKaolakuaishouHost() + uri;
        JSONArray jsonArray = commonMigrateService.pullDataFromKS(url, dto.toJSON());
        if (jsonArray.size() == 0) {
            return false;
        }
        //parse（字符串转对象）的时候 设置下划线转驼峰
        ParserConfig.getGlobalInstance().propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;

        List<UserReach> userReaches = jsonArray.toJavaList(UserReach.class);

        saveReach(userReaches);
        return true;
    }

    /**
     * 批量插入商户达标
     *
     * @param userReaches
     */
    private void saveReach(List<UserReach> userReaches) {
        List<MerchantReach20> merchantReach20List = new ArrayList<>();
        for (UserReach userReach : userReaches) {
            try {
                String userBaseId = getUserBaseId(userBaseExtMapper, userReach.getUserId(), redis);
                MerchantReach20 merchantReach20 = merchantReachMigrateService.fmtMerchantReach20Data(userReach, userBaseId);
                merchantReach20List.add(merchantReach20);
            } catch (Exception e) {
                KLog.error("迁移商户达标失败,达标记录:{}", userReach, e);
            }

        }
        if (merchantReach20List.size() != 0) {
            int i = merchantReach20Mapper.batchInsert(merchantReach20List);
            KLog.info("共[{}]条,更新[{}]条商户达标记录结束", merchantReach20List.size(), i);
        }
    }

    @Override
    public boolean migrateMerchantReachOrder(QueryTableDateDTO dto) {
        String uri = "/query/pay/base/query/order";
        String url = acmTransactionParams.getKaolakuaishouHost() + uri;
        JSONArray jsonArray = commonMigrateService.pullDataFromKS(url, dto.toJSON());
        if (jsonArray.size() == 0) {
            return false;
        }
        //parse（字符串转对象）的时候 设置下划线转驼峰
        ParserConfig.getGlobalInstance().propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;

        List<UserReach> userReaches = jsonArray.toJavaList(UserReach.class);

        updateReach(userReaches);
        return true;
    }

    private void updateReach(List<UserReach> userReachList) {
        List<MerchantReach20> insertMerchantReach20s = new ArrayList<>();
        for (UserReach userReach : userReachList) {
            try {
                String userBaseId = getUserBaseId(userBaseExtMapper, userReach.getUserId(), redis);
                MerchantReach20Example reach20Example = new MerchantReach20Example();
                reach20Example.createCriteria().andIsDelEqualTo(Constant.NORMAL)
                        .andUserBaseIdEqualTo(userBaseId)
                        .andStageEqualTo(userReach.getStage())
                        .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(userReach.getProductType()).getCode())
                        .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                List<MerchantReach20> reach20List = merchantReach20Mapper.selectByExample(reach20Example);
                MerchantReach20 merchantReach20 = merchantReachMigrateService.fmtMerchantReach20Data(userReach, userBaseId);
                if (reach20List.isEmpty()) {
                    insertMerchantReach20s.add(merchantReach20);
                } else {
                    merchantReach20.setMerchantReachId(reach20List.get(0).getMerchantReachId());
                    int i = merchantReach20Mapper.updateByPrimaryKeySelective(merchantReach20);
                    BizAssertUtils.assertOne(i, "更新商户达标失败");
                }
            } catch (Exception e) {
                KLog.error("更新达标表失败,达标数据:{}", userReach, e);
            }
        }
        if (insertMerchantReach20s.size()!=0) {
            int i = merchantReach20Mapper.batchInsert(insertMerchantReach20s);
            KLog.info("[按时间更新商户达标]插入了商户{}条,共{}条", i,insertMerchantReach20s.size());
        }
    }
}
